<template>
  <div class="app-container" v-loading="loadingV"
       element-loading-text="移动中...请耐心等待..."
       element-loading-spinner="el-icon-loading"
       element-loading-background="rgba(0, 0, 0, 0.8)">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="档号" prop="danghao">
        <el-input v-model="queryParams.danghao" placeholder="请输入档号" clearable @keyup.enter="handleQuery"/>
      </el-form-item>
      <el-form-item label="档案名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入档案名称" clearable @keyup.enter="handleQuery"/>
      </el-form-item>
      <el-form-item label="射频标签号" prop="rfid">
        <el-input v-model="queryParams.rfid" placeholder="请输入射频标签号" clearable @keyup.enter="handleQuery"/>
      </el-form-item>
      <el-form-item label="保密级别" prop="secretLevel">
        <el-select v-model="queryParams.secretLevel" placeholder="请选择保密级别" clearable>
          <el-option v-for="dict in iams_secret_level" :key="dict.value" :label="dict.label" :value="dict.value"/>
        </el-select>
      </el-form-item>
      <el-form-item label="保密期限" prop="secretPeroid">
        <el-select v-model="queryParams.secretPeroid" placeholder="请选择保密期限" clearable>
          <el-option v-for="dict in iams_secret_period" :key="dict.value" :label="dict.label" :value="dict.value"/>
        </el-select>
      </el-form-item>
      <el-form-item label="保管期限" prop="retentionPeriod">
        <el-select v-model="queryParams.retentionPeriod" placeholder="请选择保管期限" clearable>
          <el-option v-for="dict in iams_retention_period" :key="dict.value" :label="dict.label" :value="dict.value"/>
        </el-select>
      </el-form-item>
      <el-form-item label="载体类型" prop="carrierType">
        <el-select v-model="queryParams.carrierType" placeholder="请选择载体类型" clearable>
          <el-option v-for="dict in iams_carrier_type" :key="dict.value" :label="dict.label" :value="dict.value"/>
        </el-select>
      </el-form-item>
      <el-form-item label="归档时间" prop="guidangTime">
        <el-date-picker clearable v-model="queryParams.guidangTime" type="date" value-format="YYYY-MM-DD"
                        placeholder="请选择归档时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="档案状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择档案状态" clearable>
          <el-option v-for="dict in iams_archive_status" :key="dict.value" :label="dict.label" :value="dict.value"/>
        </el-select>
      </el-form-item>
      <el-form-item label="档案门类" prop="categoryId">
        <el-input v-model="queryParams.categoryId" placeholder="请输入档案门类" clearable @keyup.enter="handleQuery"/>
      </el-form-item>
      <el-form-item label="档案全宗" prop="fondsId">
        <el-input v-model="queryParams.fondsId" placeholder="请输入档案全宗" clearable @keyup.enter="handleQuery"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd"
                   v-hasPermi="['manage:archive:add']">新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
                   v-hasPermi="['manage:archive:edit']">修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
                   v-hasPermi="['manage:archive:remove']">删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
                   v-hasPermi="['manage:archive:export']">导出
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="archiveList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <!--      <el-table-column label="主键ID" align="center" prop="id">-->
      <!--        <template #default="scope">-->
      <!--          <el-link type="primary" @click="handleDetail(scope.row)" v-hasPermi="['manage:archive:query']">{{ scope.row.id }}</el-link>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <el-table-column label="档号" align="center" prop="danghao"/>
      <el-table-column label="档案名称" align="center" prop="name"/>
      <el-table-column label="射频标签号" align="center" prop="rfid"/>
      <el-table-column label="保密级别" align="center" prop="secretLevel">
        <template #default="scope">
          <dict-tag :options="iams_secret_level" :value="scope.row.secretLevel"/>
        </template>
      </el-table-column>
      <el-table-column label="保密期限" align="center" prop="secretPeroid">
        <template #default="scope">
          <dict-tag :options="iams_secret_period" :value="scope.row.secretPeroid"/>
        </template>
      </el-table-column>
      <!--      <el-table-column label="解密日期" align="center" prop="desecretDate" width="180">-->
      <!--        <template #default="scope">-->
      <!--          <span>{{ parseTime(scope.row.desecretDate, '{y}-{m}-{d}') }}</span>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <!--      <el-table-column label="保管期限" align="center" prop="retentionPeriod">-->
      <!--        <template #default="scope">-->
      <!--          <dict-tag :options="iams_retention_period" :value="scope.row.retentionPeriod"/>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <el-table-column label="载体类型" align="center" prop="carrierType">
        <template #default="scope">
          <dict-tag :options="iams_carrier_type" :value="scope.row.carrierType"/>
        </template>
      </el-table-column>
      <!--      <el-table-column label="起始时间" align="center" prop="startDate" width="180">-->
      <!--        <template #default="scope">-->
      <!--          <span>{{ parseTime(scope.row.startDate, '{y}-{m}-{d}') }}</span>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <!--      <el-table-column label="终止时间" align="center" prop="endDate" width="180">-->
      <!--        <template #default="scope">-->
      <!--          <span>{{ parseTime(scope.row.endDate, '{y}-{m}-{d}') }}</span>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <!--      <el-table-column label="归档时间" align="center" prop="guidangTime" width="180">-->
      <!--        <template #default="scope">-->
      <!--          <span>{{ parseTime(scope.row.guidangTime, '{y}-{m}-{d}') }}</span>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <el-table-column label="形成单位" align="center" prop="formationUnit"/>
      <el-table-column label="移交单位" align="center" prop="transferUnit"/>
      <el-table-column label="档案状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="iams_archive_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="档案门类" align="center" prop="categoryId"/>
      <el-table-column label="档案全宗" align="center" prop="fondsId"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" @click="handleDetail(scope.row)"
                     v-hasPermi="['manage:archive:query']">查看
          </el-button>
          <el-button link type="primary" @click="handleUpdate(scope.row)"
                     v-hasPermi="['manage:archive:edit']">修改
          </el-button>
          <el-button link type="primary" @click="handleDelete(scope.row)"
                     v-hasPermi="['manage:archive:remove']">删除
          </el-button>
          <el-button link type="primary" @click="handleBorrow(scope.row)">借阅</el-button>
          <el-button link type="primary" @click="getArchiveLog(scope.row)">日志</el-button>
          <!-- 执行移动架子操作 -->
          <el-button link type="primary" @click="handleMove(scope.row)">>移架操作<</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
                v-model:limit="queryParams.pageSize" @pagination="getList"/>

    <!-- 历史记录弹窗 -->
    <el-dialog title="档案日志" v-model="archiveLogDialogVisible" width="900px" append-to-body>
      <el-table :data="archiveLogList" style="width: 100%">
        <el-table-column type="index" label="序号" width="50" align="center"/>
        <el-table-column prop="taskType" label="任务类型" align="center"/>
        <el-table-column prop="initiator" label="发起人" align="center"/>
        <el-table-column prop="handler" label="经办人" align="center" show-overflow-tooltip/>
        <el-table-column prop="taskStatus" label="任务状态" align="center"/>
        <el-table-column prop="startDate" label="开始时间" align="center"/>
      </el-table>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="archiveLogDialogVisible = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加或修改档案列表对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="archiveRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="档号" prop="danghao">
          <el-input v-model="form.danghao" placeholder="请输入档号"/>
        </el-form-item>
        <el-form-item label="档案名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入档案名称"/>
        </el-form-item>
        <el-form-item label="射频标签号" prop="rfid">
          <el-input v-model="form.rfid" placeholder="请输入射频标签号"/>
        </el-form-item>
        <el-form-item label="保密级别" prop="secretLevel">
          <el-select v-model="form.secretLevel" placeholder="请选择保密级别">
            <el-option v-for="dict in iams_secret_level" :key="dict.value" :label="dict.label"
                       :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="保密期限" prop="secretPeroid">
          <el-select v-model="form.secretPeroid" placeholder="请选择保密期限">
            <el-option v-for="dict in iams_secret_period" :key="dict.value" :label="dict.label"
                       :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="解密日期" prop="desecretDate">
          <el-date-picker clearable v-model="form.desecretDate" type="date" value-format="YYYY-MM-DD"
                          placeholder="请选择解密日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="保管期限" prop="retentionPeriod">
          <el-select v-model="form.retentionPeriod" placeholder="请选择保管期限">
            <el-option v-for="dict in iams_retention_period" :key="dict.value" :label="dict.label"
                       :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="载体类型" prop="carrierType">
          <el-select v-model="form.carrierType" placeholder="请选择载体类型">
            <el-option v-for="dict in iams_carrier_type" :key="dict.value" :label="dict.label"
                       :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="起始时间" prop="startDate">
          <el-date-picker clearable v-model="form.startDate" type="date" value-format="YYYY-MM-DD"
                          placeholder="请选择起始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="终止时间" prop="endDate">
          <el-date-picker clearable v-model="form.endDate" type="date" value-format="YYYY-MM-DD"
                          placeholder="请选择终止时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="归档时间" prop="guidangTime">
          <el-date-picker clearable v-model="form.guidangTime" type="date" value-format="YYYY-MM-DD"
                          placeholder="请选择归档时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="实体档案位置" prop="shitiLocation">
          <el-input v-model="form.shitiLocation" placeholder="请输入实体档案位置"/>
        </el-form-item>
        <el-form-item label="电子档案位置" prop="dianziLocation">
          <el-input v-model="form.dianziLocation" placeholder="请输入电子档案位置"/>
        </el-form-item>
        <el-form-item label="档案简介" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
        <el-form-item label="形成单位" prop="formationUnit">
          <el-input v-model="form.formationUnit" placeholder="请输入形成单位"/>
        </el-form-item>
        <el-form-item label="移交单位" prop="transferUnit">
          <el-input v-model="form.transferUnit" placeholder="请输入移交单位"/>
        </el-form-item>
        <el-form-item label="文件(档)数量" prop="documentCount">
          <el-input v-model="form.documentCount" placeholder="请输入文件(档)数量"/>
        </el-form-item>
        <el-form-item label="档案状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择档案状态">
            <el-option v-for="dict in iams_archive_status" :key="dict.value" :label="dict.label"
                       :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="档案门类" prop="categoryId">
          <el-input v-model="form.categoryId" placeholder="请输入档案门类"/>
        </el-form-item>
        <el-form-item label="档案全宗" prop="fondsId">
          <el-input v-model="form.fondsId" placeholder="请输入档案全宗"/>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Archive">
import {listArchive, getArchive, delArchive, addArchive, updateArchive, ArchivePermission} from "@/api/manage/archive";
import {listArchiveLog} from "@/api/manage/ArchiveLog"
import {updateCabinetSize} from "@/api/manage/cabinet";
import {ElMessage, ElMessageBox} from "element-plus";
import {getInfo} from "@/api/system/GDIpInfo.js";
import {getColumnStatus, leftMoveColumn, rightMoveColumn, unlockColumn} from "@/api/system/move.js";

const {proxy} = getCurrentInstance();
const {
  iams_carrier_type,
  iams_archive_status,
  iams_retention_period,
  iams_secret_period,
  iams_secret_level
} = proxy.useDict('iams_carrier_type', 'iams_archive_status', 'iams_retention_period', 'iams_secret_period', 'iams_secret_level');

const archiveList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const files = ref([]);
//loadingV
let loadingV = ref(false);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    danghao: null,
    name: null,
    rfid: null,
    secretLevel: null,
    secretPeroid: null,
    retentionPeriod: null,
    carrierType: null,
    guidangTime: null,
    directory: null,
    status: null,
    categoryId: null,
    fondsId: null,
  },
  logQueryParams: {
    pageNum: 1,
    pageSize: 10,
    archiveId: null,
    taskType: null,
    initiator: null,
    handler: null,
    startDate: null,
    endDate: null,
    taskStatus: null,
  },
  rules: {
    name: [
      {required: true, message: "档案名称不能为空", trigger: "blur"}
    ],
  }
});

const {queryParams, form, rules, logQueryParams} = toRefs(data);


/** 查询档案列表列表 */
function getList() {
  loading.value = true;
  listArchive(queryParams.value).then(response => {
    archiveList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

const archiveLogDialogVisible = ref(false);
const archiveLogList = ref([]);

/** 查看档案日志 */
function getArchiveLog(row) {
  archiveLogDialogVisible.value = true;
  logQueryParams.value.archiveId = row.id;

  listArchiveLog(logQueryParams.value).then(response => {
    archiveLogList.value = response.rows;
  });
}

// 移动架子的操作handleMove   likang
async function handleMove(row) {

  // console.log('列数据',row.shitiLocation)
  const quHao = row.shitiLocation.split('-')[0]
  // .substring(0, 1);
  const lieHao = row.shitiLocation.split('-')[1]
  // .substring(0, 1);
  const AorB = row.shitiLocation.split('-')[2]
  // .substring(0, 1);


  // 判断row.shitiLocation安装位置格式是否正确
  if (row.shitiLocation.split('-').length !== 3) {
    ElMessageBox.confirm(
        '请检查档案位置格式是否正确！正确格式参考:  1-2-A;您的格式为:' + row.shitiLocation,
        '系统警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'error',
        }
    ).then(() => {

    }).catch(() => {

    });
    return;
  }
  let quHaoList = ['1', '2', '3', '4']
  let lieHaoList = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18']
  // 判断quHao是否在quHaoList中
  if (!quHaoList.includes(quHao)) {
    ElMessageBox.confirm(
        '请检查档案位置格式是否正确！正确格式参考:  1-2-A;' +
        '实际代表1区2列左边。' +
        '但是您的格式为:' + row.shitiLocation + ';请先修改。ps:区号只有1-4,列号只有1-18',
        '系统警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'error',
        }
    ).then(() => {

    }).catch(() => {

    });
    return;
  }
  // 判断lieHao是否在lieHaoList中
  if (!lieHaoList.includes(lieHao)) {
    ElMessageBox.confirm(
        '请检查档案位置格式是否正确！正确格式参考:  1-2-A;' +
        '实际代表1区2列左边。' +
        '但是您的格式为:' + row.shitiLocation + ';请先修改。ps:区号只有1-4,列号只有1-18',
        '系统警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'error',
        }
    ).then(() => {

    }).catch(() => {

    });
    return;
  }


  // 是否开架
  await proxy.$modal.confirm('是否确认打开[解锁]编号为"' + row.danghao + '"的档案所在列？具体为' + row.shitiLocation)
      .then(async () => {
        const loadingInstance = proxy.$loading({
          lock: true,
          text: "正在发送解锁指令...",
          spinner: "el-icon-loading",
        });
        // 根据 quHao查找ip和端口
        await getInfo(quHao).then(async (response) => {
          const ip = response.data.gdlIp;
          const port = response.data.gdlPort;
          // 先进行解锁操作
          await unlockColumn(ip, port).  //原
              then(async (response) => {
                // console.log('解锁返回',response)
                if (response.data.data == "1") { //原
                  loadingInstance.close();
                  ElMessage({
                    message: '列解锁成功...',
                    type: 'success',
                    duration: 1500
                  })
                  const loadingInstance2 = proxy.$loading({
                    lock: true,
                    text: "正在获取柜子状态...",
                    spinner: "el-icon-loading",
                  });
                  // 进门左手的档案柜
                  if (quHao == 1 || quHao == 2 || quHao == '1' || quHao == '2') {
                    // 看左侧
                    if (AorB == 'A') {
                      // 获取列状态
                      await getColumnStatus(ip, port)
                          .then(async (response) => {
                            loadingInstance2.close()
                            const loadingInstance3 = proxy.$loading({
                              lock: true,
                              text: "正在发送移动指令...",
                              spinner: "el-icon-loading",
                            });
                            // 列到位状态字符串：0231，说明该组密集架共有4列，
                            // 第一列状态是0，表示两边均未到位；
                            // 第二列状态是2，表示只有右边到位；
                            // 第三列状态是3，表示两边均到位；
                            // 第四列状态是1表示只有左边到位。
                            const ColumnStatus = response['data']['data'][0]['ColumnStatus']
                            // 判断ColumnStatus中第lieHao的数值
                            if (ColumnStatus[lieHao - 1] == 0 || ColumnStatus[lieHao - 1] == 1 || ColumnStatus[lieHao - 1] == 3) {
                              // 列均未到位 || 列右边未到位 || 都到位
                              await rightMoveColumn(ip, port, lieHao)
                                  .then(response => {
                                    console.log('右移1成功',response)
                                    loadingInstance3.close()
                                    if (response.data.data == "1") {
                                      console.log('右移1成功2',response)
                                      ElMessage({
                                        message: '正在移动柜子，请耐心等待，或观看监控状态',
                                        type: 'success',
                                        duration: 2500
                                      })
                                      // loadingV.value = true;
                                    }
                                  })
                                  .catch(error => {
                                    loadingInstance3.close()
                                    console.log('右移1失败',response)
                                    // ElMessage({
                                    //   message: '右移操作失败',
                                    //   type: 'error'
                                    // })
                                  });
                            } else if (ColumnStatus[lieHao - 1] == 2) {
                              //  只有右边到位，说明左边未到位，本来就是查看左边，所以不用管
                              console.log('只有右边到位，说明左边未到位，本来就是查看左边，所以不用管')
                            }
                          })
                          .catch(error => {
                            loadingInstance2.close()
                            console.log('获取列状态失败')
                          });
                    } else if (AorB == 'B') {
                      await getColumnStatus(ip, port).then(async response => {
                        loadingInstance2.close()
                        const loadingInstance3 = proxy.$loading({
                          lock: true,
                          text: "正在发送移动指令...",
                          spinner: "el-icon-loading",
                        });
                        // 列到位状态字符串：0231，说明该组密集架共有4列，
                        // 第一列状态是0，表示两边均未到位；
                        // 第二列状态是2，表示只有右边到位；
                        // 第三列状态是3，表示两边均到位；
                        // 第四列状态是1表示只有左边到位。
                        const ColumnStatus = response['data']['data'][0]['ColumnStatus']
                        // 判断ColumnStatus中第lieHao的数值
                        if (ColumnStatus[lieHao - 1] == 0 || ColumnStatus[lieHao - 1] == 2) {
                          // 列均未到位 || 列左边不到位
                          await leftMoveColumn(ip, port, lieHao)
                              .then(response => {
                                console.log('左移1成功',response)
                                loadingInstance3.close()
                                if (response.data.data == "1") {
                                  ElMessage({
                                    message: '正在移动柜子，请耐心等待，或观看监控状态',
                                    type: 'success',
                                    duration: 2500
                                  })
                                  // loadingV.value = true;
                                }
                                console.log(response);
                              })
                              .catch(error => {
                                loadingInstance3.close()
                                console.log('左移1失败',response)
                                // ElMessage({
                                //   message: '左移操作失败',
                                //   type: 'error'
                                // })
                              })
                        } else if (ColumnStatus[lieHao - 1] == 3) {
                          // 3两侧均到位      则2+1号柜子右移
                          rightMoveColumn(ip, port, lieHao + 1)
                              .then(response => {
                                console.log('右移2成功',response)
                            loadingInstance3.close()
                            if (response.data.data == "1") {
                              ElMessage({
                                message: '正在移动柜子，请耐心等待，或观看监控状态',
                                type: 'success',
                                duration: 2500
                              })
                              // loadingV.value = true;
                            }
                          })
                              .catch(error => {
                                loadingInstance3.close()
                                console.log('右移2失败',response)
                                // ElMessage({
                                //   message: '右移操作失败',
                                //   type: 'error'
                                // })
                          });
                        } else if (ColumnStatus[lieHao - 1] == 1) {
                          // 1左侧到位 就是右侧不到位
                          // 不用管
                        }
                      }).catch(error => {
                        loadingInstance2.close()
                        console.log('获取列状态失败')
                      });
                    }
                  }
                  // 进门右手的档案柜
                  else if (quHao == 3 || quHao == 4 || quHao == '3' || quHao == '4') {
                    if (AorB == 'A') {
                      // 获取列状态
                      await getColumnStatus(ip, port).then(async (response) => {
                        loadingInstance2.close()
                        const loadingInstance3 = proxy.$loading({
                          lock: true,
                          text: "正在发送移动指令...",
                          spinner: "el-icon-loading",
                        });
                        // 列到位状态字符串：0231，说明该组密集架共有4列，
                        // 第一列状态是0，表示两边均未到位；
                        // 第二列状态是2，表示只有右边到位；
                        // 第三列状态是3，表示两边均到位；
                        // 第四列状态是1表示只有左边到位。
                        const ColumnStatus = response['data']['data'][0]['ColumnStatus']
                        // 判断ColumnStatus中第lieHao的数值
                        if (ColumnStatus[lieHao - 1] == 0 || ColumnStatus[lieHao - 1] == 1) {
                          // 列均未到位 || 列右边未到位
                          await rightMoveColumn(ip, port, lieHao)
                              .then(response => {
                                console.log('右移3成功',response)
                                loadingInstance3.close()
                            if (response.data.data == "1") {
                              loadingInstance3.close()
                              ElMessage({
                                message: '正在移动柜子，请耐心等待，或观看监控状态',
                                type: 'success',
                                duration: 2500
                              })
                            }
                          })
                              .catch(error => {
                                loadingInstance3.close()
                                console.log('右移3失败',response)
                          });
                        } else if (ColumnStatus[lieHao - 1] == 3) {
                          await leftMoveColumn(ip, port, lieHao + 1)
                              .then(response => {
                                console.log('左移2成功',response)
                                loadingInstance3.close()
                                if (response.data.data == "1") {
                                  ElMessage({
                                    message: '正在移动柜子，请耐心等待，或观看监控状态',
                                    type: 'success',
                                    duration: 2500
                                  })
                                }
                              })
                              .catch(error => {
                                loadingInstance3.close()
                                console.log('左移2失败',response)
                                // ElMessage({
                                //   message: '左移操作失败',
                                //   type: 'error'
                                // })
                              });
                        } else if (ColumnStatus[lieHao - 1] == 2) {
                          // 不用管
                          console.log('')
                        }
                      }).catch(error => {
                        loadingInstance2.close()
                        console.log('获取列状态失败')
                      });
                    }
                    else if (AorB == 'B') {
                      await getColumnStatus(ip, port).then(async (response) => {
                        loadingInstance2.close()
                        const loadingInstance3 = proxy.$loading({
                          lock: true,
                          text: "正在发送移动指令...",
                          spinner: "el-icon-loading",
                        });
                        const ColumnStatus = response['data']['data'][0]['ColumnStatus']
                        if (ColumnStatus[lieHao - 1] == 0 || ColumnStatus[lieHao - 1] == 2 || ColumnStatus[lieHao - 1] == 3) {
                          await leftMoveColumn(ip, port, lieHao)
                              .then(response => {
                                console.log('左移3成功',response)
                                loadingInstance3.close()
                            if (response.data.data == "1") {
                              ElMessage({
                                message: '正在移动柜子，请耐心等待，或观看监控状态',
                                type: 'success',
                                duration: 2500
                              })
                            }
                          })
                              .catch(error => {
                                loadingInstance3.close()
                                console.log('左移3失败',response)

                            // ElMessage({
                            //   message: '左移操作失败',
                            //   type: 'error'
                            // })
                          });
                        } else if (ColumnStatus[lieHao - 1] == 1) {
                          console.log('不用管')
                        }
                      }).catch(error => {
                        loadingInstance2.close()
                      });
                    }
                  }
                }
              })
              .catch(error => {
                loadingInstance.close();
                ElMessage({
                  message: '解锁失败',
                  type: 'error',
                  duration: 5000
                })
              })
        });
      })
      .catch(() => {
      });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    danghao: null,
    name: null,
    rfid: null,
    jianhao: null,
    secretLevel: null,
    secretPeroid: null,
    desecretDate: null,
    retentionPeriod: null,
    carrierType: null,
    startDate: null,
    endDate: null,
    guidangTime: null,
    shitiLocation: null,
    dianziLocation: null,
    directory: null,
    description: null,
    formationUnit: null,
    transferUnit: null,
    documentCount: null,
    status: null,
    authenticity: null,
    integrity: null,
    availability: null,
    security: null,
    categoryId: null,
    fondsId: null,
    createTime: null,
    createBy: null,
    updateTime: null,
    updateBy: null,
    remark: null
  };
  proxy.resetForm("archiveRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  proxy.$router.push({path: "/manage/archive/arc-add"});
}

/** 查看详情操作 */
function handleDetail(row) {
  ArchivePermission(row.id).then(response => {
    if (response.data) {
      proxy.$router.push({path: "/manage/archive/arc-detail", query: {id: row.id}});
    } else {
      proxy.$modal.msgError("您没有权限查看，请先提交借阅申请");
    }
  });
}

/** 修改按钮操作 */
function handleUpdate(row) {
  proxy.$router.push({path: "/manage/archive/arc-edit", query: {id: row.id}});
}

/** 借阅按钮操作 */
function handleBorrow(row) {
  proxy.$router.push({path: "/manage/record", query: {record_id: row.id, record_name: row.name}});
}

/** 删除按钮操作 */
function handleDelete_process(row) {
  proxy.$router.push({
    path: "/manage/archive/ArchiveDestroyRecord",
    query: {delete_id: row.id, delete_name: row.name, delete_danghao: row.danghao}
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["archiveRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateArchive(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addArchive(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
async function handleDelete(row) {
  // 如果 row 存在，则使用 row.id，否则使用 ids.value
  let _ids = row.id ? [row.id] : ids.value;
  if (_ids.length > 1) {
    proxy.$modal.msgError("请勿批量删除档案！");
    return;
  }
  for (const id of _ids) {
    try {
      const response = await getArchive(id);
      // console.log('response.data.directory:', response.data.directory);

      // 确保 directory 是一个数组
      let directoryArray = [];
      if (response.data.directory) {
        directoryArray = JSON.parse(response.data.directory);
      }
      console.log("当前档案的目录结构：", directoryArray);

      // 收集所有 files 的值
      files.value = collectAllFileIds(directoryArray);
      console.log("当前档案的文档列表：", files.value);

      // 确认删除
      await proxy.$modal.confirm(`是否确认删除档案列表编号为"${id}"的数据项？`);
      // console.log(row);

      let canDelete = 0;
      if (response.data.carrierType === 'Mixture') {
        if (files.value.length > 0) {
          proxy.$modal.msgError("电子档案中还有文档！");
        } else if (response.data.status !== 'Destroyed') {
          proxy.$modal.msgError("实体档案还未销毁！");
          proxy.$router.push({
            path: "/manage/archive/ArchiveDestroyRecord",
            query: {id: response.data.id, name: response.data.name, danghao: response.data.danghao}
          });
        } else {
          canDelete = 1
        }
      } else if (response.data.carrierType === 'electronic') {
        if (files.value.length > 0) {
          proxy.$modal.msgError("电子档案中还有文档！");
        } else {
          canDelete = 1
        }
      } else if (response.data.carrierType === 'tangible') {
        if (response.data.status !== 'Destroyed') {
          proxy.$modal.msgError("实体档案还未销毁！");
          proxy.$router.push({
            path: "/manage/archive/ArchiveDestroyRecord",
            query: {id: response.data.id, name: response.data.name, danghao: response.data.danghao}
          });
        } else {
          canDelete = 1
        }
      }
      if (canDelete === 1) {
        delArchive(id).then(response => {
          if (response.code === 200) {
            updateCabinetSize(response.data.shitiLocation, "delete")
            getList();
            proxy.$modal.msgSuccess("删除成功");
          }
        });
      }
    } catch (error) {
      proxy.$modal.msgError("删除操作取消或出错");
      console.error('删除操作取消或出错:', error);
    }
  }
}

function collectFileIds(data) {
  let fileIds = [];

  // 如果当前节点有 files 属性，则将其添加到结果数组中
  if (data.files) {
    fileIds = fileIds.concat(data.files);
  }

  // 如果当前节点有 children 属性，则递归处理每个子节点
  if (data.children && data.children.length > 0) {
    data.children.forEach(child => {
      fileIds = fileIds.concat(collectFileIds(child));
    });
  }

  return fileIds;
}

// 处理整个数组
function collectAllFileIds(directory) {
  let allFileIds = [];

  directory.forEach(item => {
    allFileIds = allFileIds.concat(collectFileIds(item));
  });

  return allFileIds;
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('manage/archive/export', {
    ...queryParams.value
  }, `archive_${new Date().getTime()}.xlsx`)
}

getList();
</script>
